package com.feihong.zhiwenlibrary.zhiwen;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.feihong.zhiwenlibrary.R;
import com.feihong.zhiwenlibrary.bean.FingerprintIdentify;
import com.feihong.zhiwenlibrary.bean.base.BaseFingerprint;

public class ZhiWenDialog
        extends DialogFragment {

    private static final String TAG = "指纹";
    Dialog mDialog;
    LinearLayout ll_btn;
    TextView tv_msg;
    ImageView iv;

    private ZhiWenCallBack mCallback;

    private FingerprintIdentify mFingerprintIdentify;

    private static final int MAX_AVAILABLE_TIMES = 3;
    private boolean isEnableFinger = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (mDialog == null) {
            mDialog = new Dialog(getActivity(), R.style.petgirls_dialog);
            mDialog.setContentView(R.layout.password_dialog_fragment_finger);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.getWindow().setGravity(Gravity.CENTER);
            View view = mDialog.getWindow().getDecorView();
            tv_msg = (TextView) view.findViewById(R.id.tv_msg);
            ll_btn = (LinearLayout) view.findViewById(R.id.ll_btn);
            iv = (ImageView) view.findViewById(R.id.iv);
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

//            view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (mCallback != null) {
//                        mCallback.onShowPwdDialog();
//                    }
//                    dismiss();
//                }
//            });

        }

        return mDialog;
    }


    public void setZhiWenCallBack(ZhiWenCallBack mFragmentCallBack) {
        this.mCallback = mFragmentCallBack;
    }

    @Override
    public void onResume() {
        super.onResume();
        // mFingerprintIdentify.resumeIdentify();
    }

    private void start() {


    }

    FingerListener exceptionListener = new FingerListener() {

        @Override
        public void onCatchException(Throwable exception) {

            Log.e(TAG, "指纹识别 onCatchException: ", exception);
            if (mCallback != null) {
                mCallback.onError("出错，无法正常使用指纹硬件，请用密码支付!");
            }
            dismiss();
        }

        @Override
        public void onSucceed() {

            Log.i(TAG, "指纹识别 onSucceed: ");
            if (mCallback != null) {
                mCallback.onSuccess();
            }
            dismiss();
        }

        @Override
        public void onNotMatch(int availableTimes) {
            Log.i(TAG, "指纹识别 onNotMatch: " + availableTimes);
            shake(iv);
        }

        @Override
        public void onFailed(boolean isDeviceLocked) {
            Log.i(TAG, "指纹识别 onFailed: " + isDeviceLocked);
            if (mCallback != null) {
                mCallback.onError("指纹验证失败，请用密码支付！");
            }
            dismiss();
        }

        @Override
        public void onStartFailedByDeviceLocked() {
            Log.i(TAG, "指纹识别 onStartFailedByDeviceLocked: ");
            if (mCallback != null) {
                mCallback.onError("验证指纹失败频率高，稍后再试!");
            }
            dismiss();
        }
    };

    @Override
    public void show(FragmentManager manager, String tag) {
        super.show(manager, tag);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                kaishishibie();
            }
        }, 500);
    }

    /***
     * 判断是否支持指纹功能
     * @return
     */
    public boolean isFingerprintEnable() {
        try {
            if (!isEnableFinger) {
                return isEnableFinger;
            }
            if (mFingerprintIdentify != null) {
                return mFingerprintIdentify.isFingerprintEnable();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;

    }

    private void kaishishibie() {
        try {
            if (mFingerprintIdentify == null || !isEnableFinger) {
                if (mCallback != null) {
                    mCallback.onError("此设备不支持指纹功能，请用密码支付！");
                }
                //        dismiss();
                return;
            }
            if (!mFingerprintIdentify.isFingerprintEnable()) {
                Log.i(TAG, "password_dialog_zhiwen: 是否支持指纹:" + mFingerprintIdentify.isFingerprintEnable());
                if (mCallback != null) {
                    mCallback.onError("此设备不支持指纹功能，请用密码支付！");
                }
                //  dismiss();
                return;
            }
            //  mFingerprintIdentify.isFingerprintEnable();                                 // 指纹硬件可用并已经录入指纹
            boolean isHardwareEnable = mFingerprintIdentify.isHardwareEnable();// 指纹硬件是否可用
            Log.i(TAG, "password_dialog_zhiwen: 指纹硬件是否可用:" + isHardwareEnable);
            if (!isHardwareEnable) {
                if (mCallback != null) {
                    mCallback.onError("无法注册指纹硬件，请用密码支付！");
                }
                // dismiss();
                return;
            }
            boolean isRegisteredFingerprint = mFingerprintIdentify.isRegisteredFingerprint();
            Log.i(TAG, "password_dialog_zhiwen: 注册指纹硬件:" + isRegisteredFingerprint);
            if (!isRegisteredFingerprint) {
                if (mCallback != null) {
                    mCallback.onError("手机没有开启指纹功能，请用密码支付！");
                }
                //dismiss();
                return;
            }
            mFingerprintIdentify.startIdentify(3, exceptionListener);
        } catch (Exception ex) {
            if (mCallback != null) {
                mCallback.onError("出错，请用密码支付！");
            }
            Log.e(TAG, "指纹: ", ex);
            //  dismiss();
        }
    }

    public void init(Context context) {
        try {
            mFingerprintIdentify = new FingerprintIdentify(context, new BaseFingerprint.FingerprintIdentifyExceptionListener() {

                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG, "onCatchException: 无法初始化指纹设备，肯能此设备不支持指纹功能...", exception);
                    isEnableFinger = false;
                }
            });                      // 构造对象
            // mFingerprintIdentify = new FingerprintIdentify(this, exceptionListener);    // 构造对象，并监听错误回调（错误仅供开发使用）
        } catch (Exception ex) {
            Log.e(TAG, "无法初始化指纹设备，可能设备不支持指纹支付", ex);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        //  mFingerprintIdentify.cancelIdentify();
    }

    private void shake(View v) {
        Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.password_dialog_shake);
        v.startAnimation(shake);
    }

    @Override
    public void onDestroy() {
        try {
            if (mFingerprintIdentify != null) {
                mFingerprintIdentify.cancelIdentify();
            }
        } catch (Exception ex) {
        }

        super.onDestroy();
        mCallback = null;

    }

}
